package com.clss.emergencycall.utils;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Vibrator;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.amap.api.location.AMapLocation;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.LazyHeaders;
import com.bumptech.glide.request.target.SimpleTarget;
import com.clss.emergencycall.view.NormalFragmentDialog;
import com.google.android.material.snackbar.Snackbar;
import com.clss.emergencycall.base.BaseActivity;
import com.clss.emergencycall.base.Constant;
import com.clss.emergencycall.EmergencyApplication;
import com.clss.emergencycall.tools.eventbus.EventBusHelper;
import com.clss.emergencycall.tools.eventbus.EventBusMessage;
import com.clss.emergencycall.utils.Lg;
import com.clss.emergencycall.utils.SpHelper;
import com.clss.emergencycall.utils.VersionUpdataHelper;

import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 唐浩 on 2018/3/15.
 */

public  class PublicUtils {
    private static final String TAG = "PublicUtils";
    /***
     * 以下为吊起 高德百度地图
     */

    private static PackageManager mPackageManager = EmergencyApplication.Companion.getAppContext().getPackageManager();
    private static List<String> mPackageNames = new ArrayList<>();
    private static final String GAODE_PACKAGE_NAME = "com.autonavi.minimap";
    private static final String BAIDU_PACKAGE_NAME = "com.baidu.BaiduMap";


    private static void initPackageManager() {

        List<PackageInfo> packageInfos = mPackageManager.getInstalledPackages(0);

        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                mPackageNames.add(packageInfos.get(i).packageName);
            }
        }
    }

    public static boolean haveGaodeMap() {
        initPackageManager();
        return mPackageNames.contains(GAODE_PACKAGE_NAME);
    }

    public static boolean haveBaiduMap() {
        initPackageManager();
        return mPackageNames.contains(BAIDU_PACKAGE_NAME);
    }

    public static void showUrlImage(Context context, String url, SimpleTarget<Drawable> simpleTarget) {
        LazyHeaders headers = new LazyHeaders
                .Builder()
                .addHeader(Constant.APP_TOKEN, SpHelper.getInstance().getToken())
                .build();
        GlideUrl glideUrl = new GlideUrl(url, headers);
        Glide.with(context).load(glideUrl).into(simpleTarget);
    }


    public static void showFragmentDialog(BaseActivity mContext, String content, NormalFragmentDialog.OkView view) {
        NormalFragmentDialog.getInstance()
                .getTvContent(content)
                .setStrOk("确定")
                .setStrCancel("取消")
                .setokListener(view).show(mContext.getFragmentManager(), "");
    }

    /**
     * 走马灯textview
     */
    public static void setTextMarquee(TextView textView, String s) {
        if (textView != null) {
            textView.setText(s + "的报警正在处理中,点击查看");
            textView.setEllipsize(TextUtils.TruncateAt.MARQUEE);
            textView.setSingleLine(true);
            textView.setSelected(true);
            textView.setFocusable(true);
            textView.setFocusableInTouchMode(true);
        }
    }


    /***
     *  用户主动选择地址后的处理 存储数据 修改地址（选择地址修改）
     *  吧选择的code码
     */
    public static void changeSite(Context context, String adCode, String provice, String city, String area) {
        Lg.i(TAG, "changeSite: ");
        EventBusHelper.sendEventBusMsg(EventBusHelper.STOP_STOMP_KEEP_ALIVE);
        SpHelper.getInstance().putAllSite(adCode, provice, city, area);
//        PublicUtils.changeLogo(adCode);
    }

    /***
     *  移动到其他区 修改地址（定位修改）
     */
    public static void changeSite(Context context, AMapLocation location) {
//        String serCode = SpHelper.getInstance().getString(SpHelper.AMAPLOCATION_INFO_AREA);  //后端的code码
        String lastCode = SpHelper.getInstance().getString(SpHelper.LOCATION_AREA_CODE);  //上一个定位的code码
        String inCode = location.getAdCode();  //现在的code
        String fenceCode = SpHelper.getInstance().getString(SpHelper.FENCE_ID); //围栏区域
        Lg.i(TAG, "---changeSite==lastCode=" + lastCode);
        Lg.i(TAG, "---changeSite==inCode=" + inCode);
        Lg.i(TAG, "---changeSite==fenceCode=" + fenceCode);
        if (!lastCode.equals(inCode) && !inCode.isEmpty() && fenceCode.isEmpty()) {
//            changeLogoService(inCode);
            SpHelper.getInstance().putAllSite();
            EventBusHelper.sendEventBusMsg(EventBusMessage.UPDATA_ALL_MODO_SERVICE);
        }
    }

    public static void changeLogoService(String newCode) {
        String localCodeYop = SpHelper.getInstance().getLocation().getAreacode().substring(0, 2);
        String newCodeTop = newCode.substring(0, 2);
        if (!localCodeYop.equals(newCodeTop)) {
//            changeLogo(newCode);
        }
    }


    public static final String[] COMPOMENT_LIST = {"com.clss.emergencycall.Activity.common.SplashActivity"
            , "com.clss.emergencycall.Function.login.HeBei", "com.clss.emergencycall.Function.login.JiangShu"};
    private static final String[] CODE_YOP_SITE = {"", "13", "32"};
    public static final String CODE_HEBEI = "13";
    public static final String CODE_JIANG_SHU = "32";


//    public static void changeLogo(String adCode) {
//        if (!adCode.isEmpty()) {
//            switch (adCode.substring(0, 2)) {
//                case CODE_HEBEI:
//                    changeComument(COMPOMENT_LIST[1]);
//                    break;
//                case CODE_JIANG_SHU:
//                    changeComument(COMPOMENT_LIST[2]);
//                    break;
//                default:
//                    changeComument(COMPOMENT_LIST[0]);
//                    break;
//            }
//        }
//    }

    /** 计算两点间距离 */
    public static int getTance(double lat1, double lng1, double lat2, double lng2) {
        lat1 = lat1 * (Math.PI / 180);
        lat2 = lat2 * (Math.PI / 180);
        lng1 = lng1 * (Math.PI / 180);
        lng2 = lng2 * (Math.PI / 180);
        double ban = 6371.0;
        double d = Math.acos(Math.sin(lat1) * Math.sin(lat2)
                + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lng2 - lng1)) * ban * 1000;
        return (int) d;
    }

    /**
     * 启用某个地区的组件 切换图标
     */
    public static void enableCompoment(String currentName) {
        Context context = EmergencyApplication.Companion.getAppContext();
        PackageManager packageManager = context.getPackageManager();
        ComponentName HeBeiComponent = new ComponentName(context, currentName);
        int state = packageManager.getComponentEnabledSetting(HeBeiComponent);
        if (state == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
            //已经启用
            return;
        }
        try {
            packageManager.setComponentEnabledSetting(HeBeiComponent,
                    PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                    PackageManager.DONT_KILL_APP);
        }catch (IllegalArgumentException e){
            e.printStackTrace();
            Lg.i(TAG, "enableCompoment: 添加图标失败");
        }

    }

    /** 初始化页面图标 · 并重新记录图标位置*/
    public static void initCompoment(){
        for (int i = 0; i < COMPOMENT_LIST.length; i++) {
            if (i == 0){
                enableCompoment(COMPOMENT_LIST[i]);
            }else {
                disenableCompoment(COMPOMENT_LIST[i]);
            }
        }
//        changeLogo(SpHelper.getInstance().getLocation().getAreacode());
    }

    /**
     * 禁用某个地区的组件 切换图标
     */
    public static void disenableCompoment(String componentName) {
        Context context = EmergencyApplication.Companion.getAppContext();
        PackageManager packageManager = context.getPackageManager();
        ComponentName HeBeiComponent = new ComponentName(context, componentName);
        int state = packageManager.getComponentEnabledSetting(HeBeiComponent);
        if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
            //已经禁用
            return;
        }
        try {
            packageManager.setComponentEnabledSetting(HeBeiComponent,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    PackageManager.DONT_KILL_APP);
        }catch (IllegalArgumentException e){
            e.printStackTrace();
            Lg.e(TAG, "enableCompoment: 删除图标失败");
        }

    }

    /**
     * 遍历所有组件，若正在使用的不是目标组件 禁用它 并开启目标组件（记录一个需要开启和一个需要关闭的）
     */
    private static void changeComument(String Name) {
        Context context = EmergencyApplication.Companion.getAppContext();
        PackageManager packageManager = context.getPackageManager();
        for (int i = 0; i < COMPOMENT_LIST.length; i++) {
            String componentName = COMPOMENT_LIST[i];
            ComponentName component = new ComponentName(context, componentName);
            int state = packageManager.getComponentEnabledSetting(component);

            /** 这个是主页那个 */
            if (state == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT && i == 0 && !Name.equals(COMPOMENT_LIST[0])) {
                SpHelper.getInstance().putString(Constant.CHANGE_APP_LOGO_DISENABLE, COMPOMENT_LIST[0]);
            }

            if (Name.equals(componentName)) {
                if (state != PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
                    SpHelper.getInstance().putString(Constant.CHANGE_APP_LOGO_ENABLE, componentName);
                }
            } else {
                if (state == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
                    SpHelper.getInstance().putString(Constant.CHANGE_APP_LOGO_DISENABLE, componentName);
                }
            }

        }
    }

    /**
     * 判断是否包含SIM卡
     *
     * @return 状态
     */
    public static boolean ishasSimCard(Context context) {
        TelephonyManager telMgr = (TelephonyManager)
                context.getSystemService(Context.TELEPHONY_SERVICE);
        int simState = 0;
        if (telMgr != null) {
            simState = telMgr.getSimState();
        }
        boolean result = true;
        switch (simState) {
            case TelephonyManager.SIM_STATE_ABSENT:
                result = false; // 没有SIM卡
                break;
            case TelephonyManager.SIM_STATE_UNKNOWN:
                result = false;
                break;
        }
        Lg.d(TAG, result ? "有SIM卡" : "无SIM卡");
        return result;
    }

    /**
     * 播放本地视频
     */
    public static void openVideo(Context context, String filePath) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri uri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName()
                    + ".FileProvider", new File(filePath));
            intent.setDataAndType(uri, "video/*");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            context.startActivity(intent);
        } catch (Exception e) {
            Lg.i("openVideo", e.getMessage());
        }

    }

    /**
     * 根据路径获取uri
     */
    public static Uri getUri(Context c, String path) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return FileProvider.getUriForFile(c,
                    c.getApplicationContext().getPackageName() + ".FileProvider",
                    new File(path));
        } else {
            return Uri.fromFile(new File(path, ""));
        }
//        Uri uri = FileProvider.getUriForFile(FullImageActivity.this,
//                FullImageActivity.this.getApplicationContext().getPackageName()
//                        +".provider",new File(fullImageInfo.getImageUrl()));
    }

    public static Uri getAudioUri(Context c, String path) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return FileProvider.getUriForFile(c,
                    c.getApplicationContext().getPackageName() + ".FileProvider",
                    new File(path));
        } else {
            return Uri.parse(path);
        }

    }

    public static void setSpanForEndRecord(TextView textView, int startNum, int endNum, int color) {
        SpannableStringBuilder builder = new SpannableStringBuilder(textView.getText().toString());
        ForegroundColorSpan redSpan = new ForegroundColorSpan(ContextCompat.getColor(EmergencyApplication.Companion.getAppContext(), color));
        builder.setSpan(redSpan, startNum, endNum, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(builder);
    }

    /**
     * 振动手机 震动手机
     */
    public static void setViBrator() {
        Lg.i(TAG, "setViBrator: 震动手机");
        Vibrator mVibrator;
        mVibrator = (Vibrator) EmergencyApplication.Companion.getAppContext().getSystemService(Service.VIBRATOR_SERVICE);
        if (mVibrator != null) {
            mVibrator.vibrate(new long[]{100, 100, 100, 1000}, -1);
        }
    }


    public static void showInteractionDialog(String msg, boolean cancelable, String ok, String no,
                                             DialogInterface.OnClickListener okListener, Context context) {
        VersionUpdataHelper.CustomDialog.Builder builder = new VersionUpdataHelper.CustomDialog.Builder(context);
        builder.setMessage(msg);
        builder.setPositiveButton(no, (dialog,which) -> dialog.dismiss());
        builder.setNegativeButton(ok, okListener);
        VersionUpdataHelper.CustomDialog dialog = builder.create();
        dialog.setCancelable(cancelable);
        dialog.show();
    }


    /**
     * 播放一个挂断视频的声音
     * for example R.raw.wechat_video
     */
    public static MediaPlayer playAssetMusic(int id) {
        MediaPlayer mMediaPlayer = MediaPlayer.create(EmergencyApplication.Companion.getAppContext(), id);
        mMediaPlayer.setLooping(false);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.start();
        mMediaPlayer.setOnCompletionListener(mp -> mp.release());
        return mMediaPlayer;
    }


    public static MediaPlayer buildMediaPlayer(int id, Context activity, MediaPlayer.OnPreparedListener listener) {
        MediaPlayer mediaPlayer = null;
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);// 设置媒体流类型
            mediaPlayer.setOnPreparedListener(listener);
            mediaPlayer.reset();
            AssetFileDescriptor file = activity.getResources().openRawResourceFd(
                    id);
            mediaPlayer.setDataSource(file.getFileDescriptor(),
                    file.getStartOffset(), file.getLength());
            file.close();
            mediaPlayer.prepare();
        } catch (Exception e) {
            Lg.i(TAG, "init: 音乐播放已抛出异常");
            e.printStackTrace();
        }
        return mediaPlayer;
    }

    /**
     * 优先获取后端code 若空则获取定位code
     */
    @Nullable
    public static String getPriorityCode() {
        return SpHelper.getInstance().getLocation().getAreacode();
    }

    /**
     * base64转为bitmap
     */
    public static Bitmap base64ToBitmap(String base64Data) {
        byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    public static Snackbar snackBar(View view, String content, int Snackbar_Type, View.OnClickListener listener) {
        Snackbar snackbar = Snackbar.make(view, content, Snackbar_Type);
        snackbar.setAction("关闭", listener);
        return snackbar;
    }



    /**
     * 压缩bitmap尺寸
     */
    public static Bitmap compressImageSizeAndLoadBitmap(String imgpath, ImageView imageView) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(imgpath, newOpts);
        newOpts.inJustDecodeBounds = false;
        int oldWidth = newOpts.outWidth;
        int oldHeight = newOpts.outHeight;
        if (newOpts.outHeight > newOpts.outWidth) {
            oldWidth = newOpts.outHeight;
            oldHeight = newOpts.outWidth;
        }
        int scale = 1;
//		if (oldWidth / imageView.getWidth() > oldHeight / imageView.getHeight()) {
//			scale = oldWidth / imageView.getWidth();
//		} else {
//			scale = oldHeight / imageView.getHeight();
//		}
        if (scale <= 0) {
            scale = 1;
        }
        newOpts.inSampleSize = scale;
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
        bitmap = BitmapFactory.decodeFile(imgpath, newOpts);
        return bitmap;
    }

    public static Bitmap decodeSampledBitmapFromFile(String pathName, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(pathName, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        Bitmap src = BitmapFactory.decodeFile(pathName, options);
        return createScaleBitmap(src, reqWidth, reqHeight, options.inSampleSize);
    }



    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // 源图片的高度和宽度
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }

    private static Bitmap createScaleBitmap(Bitmap src, int dstWidth, int dstHeight, int inSampleSize) {
// 如果是放大图片，filter决定是否平滑，如果是缩小图片，filter无影响，我们这里是缩小图片，所以直接设置为false
        Bitmap dst = Bitmap.createScaledBitmap(src, dstWidth, dstHeight, false);
        if (src != dst) { // 如果没有缩放，那么不回收
            src.recycle(); // 释放Bitmap的native像素数组
        }
        return dst;
    }

}
